<template>
    <el-container>
        <el-aside width="400px">
            <el-container>
                <el-header style="height:50px;display: flex;justify-content: center; align-items: center">
                    <el-input placeholder="输入关键字进行过滤" v-model="menuFilterText" clearable></el-input>
                    <el-button icon="el-icon-refresh" type="primary" @click="onRefreshMenuTree()" style="margin-left: 5px"/>
                </el-header>
                <el-main class="kt-main" v-loading="menuLoading" style="padding: 0;">
                    <el-tree ref="menuRef"
                             :accordion="false"
                             :check-strictly="true"
                             :data="menus"
                             :expand-on-click-node="true"
                             :filter-node-method="menuFilterNode"
                             :highlight-current="true"
                             :props="menuProps"
                             class="menu"
                             node-key="menuId"
                             @node-click="menuClick">
                        <template #default="{ node, data }">
                            <span class="custom-tree-node el-tree-node__label">
                                <span class="label">
                                    <el-icon>
                                        <svg-icon :icon="data.icon"/>
                                    </el-icon>
                                    <span style="margin-left: 5px">{{ node.label }}</span>
                                </span>
                               <i class="el-icon do" v-if="data.type !== '2'" v-auth="'menu:add'" @click.stop="onCreate(data, node)"/>
                            </span>
                        </template>
                    </el-tree>
                </el-main>
                <el-footer style="height:42px;border: 1px dashed var(--el-border-color)">
                    <el-button v-auth="'menu:add'" style="width: 100%;"  link @click="onCreate({menuId: '0', parentId: '0'})"></el-button>
                </el-footer>
            </el-container>
        </el-aside>
        <el-container>
            <el-main ref="mainRef" class="kt-main" style="padding:20px;">
                <edit ref="editRef" :save="onSave" :remove="onDelete" :menu="menus" :node="currentNode"/>
            </el-main>
        </el-container>
    </el-container>
</template>

<script lang="ts" setup>
import {onBeforeMount, reactive, ref, watch} from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import Edit from './edit.vue'
import {service} from '@/utils'
import SvgIcon from "@/components/svg-icon/index.vue";
import {getMenuTreeByType} from "@/api/system";

const menuRef = ref()
const editRef = ref()
const mainRef = ref()

const menuLoading = ref(false);
const menus = ref<Array<{[key:string]:any}>>([])
const menuProps = reactive({
    label: (data: any) => {
        return data.title
    },
    class: (data: any) => {
        return data.menuId === '0'? 'el-tree-node__plus':''
    }
})

//树点击
const currentNode = ref();
const menuClick = (data: any, node: any) => {
    currentNode.value = node;
    mainRef.value.$el.scrollTop = 0
}

//树过滤
const menuFilterText = ref('')
const menuFilterNode = (value: any, data: any) => {
    if (!value) return true;
    return data.menuId !== '0' && data.title.indexOf(value) !== -1;
}
watch(menuFilterText, (val) => menuRef.value.filter(val))

// 刷新
const onRefreshMenuTree = () => {
    menuFilterText.value = ''
    menuLoading.value = true;
    getMenuTreeByType().then(({code, data}) => {
        if (code === 200) {
            menus.value = data.rows
        }
    }).finally(() => menuLoading.value = false)
}

//增加
const onCreate = async (data?: any, node?: Node) => {
    let order;
    if (data.menuId !== '0') {
        order = (data?.children?.at(-1)?.orderNum || -5) + 5;
    } else {
        order = (menus.value.filter(item => item.type === '0').at(-1)?.orderNum || 0) + 10;
    }
    onSave({
        menuId: null,
        icon: '',
        type: '0',
        title: '未命名',
        parentId: data.menuId,
        perms: '',
        path: data.path? (data.path + '/'):'',
        code: data.code? data.code:'AdminApplication',
        component: data.menuId == '0'? 'PageView':'',
        orderNum: order,
        params: null
    }, node)
}

// 新增&修改 菜单/按钮信息
const onSave = (form: any, node?: Node) => {
    service[form.menuId? 'put':'post']('/menu', form).then(({code, data}) => {
        if (code === 200) {
            if (form.menuId) {
                // 修改菜单信息后更新菜单树节点信息
                // 除上级菜单和序号变更外其他信息修改则只需要覆盖信息即可
                // if ((currentNode.value.data.parentId === form.parentId)
                //         && (currentNode.value.data.orderNum === form.orderNum)){
                //     Object.assign(currentNode.value.data, form)
                //     menuRef.value.updateKeyChildren(form.menuId, node.data)
                // } else {
                //     onRefreshMenuTree();
                // }
                onRefreshMenuTree();
                //手动变更位置
                // if (rs) {
                //     Object.assign(node.data, form);
                //     let datas: any[];
                //     menuRef.value.remove(form.menuId);
                //     if (form.parentId === '0') {
                //         datas = menus.value.slice(0, -1);
                //     } else {
                //         const parent = menuRef.value.getNode(form.parentId);
                //         datas = parent.data.children || []
                //     }
                //     datas.reduce((previousValue, currentValue, currentIndex: number) => {
                //         if (currentIndex === 0 && currentValue.orderNum >= form.orderNum) {
                //              menuRef.value.insertBefore(node.data, currentValue.menuId);
                //         } else if (previousValue.orderNum < form.orderNum && currentValue.orderNum >= form.orderNum){
                //             menuRef.value.insertAfter(node.data, previousValue.menuId);
                //         } else if (datas.length - currentIndex === 1 && currentValue.orderNum < form.orderNum) {
                //             menuRef.value.insertAfter(node.data, currentValue.menuId);
                //         }
                //         return currentValue;
                //     })
                // }
            } else {
                //追加根节点/子节点
                if (node) {
                    menuRef.value.append(data, node);
                } else {
                    menuRef.value.append(data);
                }
                // 重新选中菜单
                menuRef.value.setCurrentKey(data.menuId);
                currentNode.value = menuRef.value.getNode(data.menuId);
                // 新增菜单后数据源也会新增
                // console.log(menus.value)
            }
        }
    })
}

//删除菜单
const onDelete = (data: any) => {
    service.confirm(`确定对菜单[${data.title}]包含子菜单进行删除操作,该操作不可逆?`, {
        url: '/menu',
        data: {menuIds: [data.menuId]},
        success: () => {
            currentNode.value = undefined;
            menuRef.value.remove(data.menuId);
        }
    })
}

onBeforeMount(() => {
    onRefreshMenuTree()
})
</script>
<style scoped>


.custom-tree-node {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: space-between;
    font-size: 15px;
    padding-right: 24px;
    height: 100%;
}

.custom-tree-node .label {
    display: flex;
    align-items: center;;
    height: 100%;
}

.custom-tree-node .label .el-tag {
    margin-left: 5px;
}

.custom-tree-node .do {
    display: none;
}

.custom-tree-node .do i {
    color: #999;
}

.custom-tree-node .do i:hover {
    color: #333;
}

.custom-tree-node:hover .do {
    display: inline-block;
}

.el-tree-node__plus .custom-tree-node{
    justify-content: center;
}
</style>
